<template>
	<div class="app-layout">
		<CharacterSelector
				:characters="characters"
				:current-character="currentCharacter"
				@select-character="selectCharacter"
				@manage-characters="goToCharacterManagement"
				@clone-voice="handleCloneVoice"
				@manage-knowledge="goToKnowledgeManagement"
				@logout="handleLogout"
		/>
		
		<div class="main-layout">
			<HistoryPanel
					:chat-sessions="chatSessions"
					:current-session-id="currentSessionId"
					@load-session="loadSession"
					@create-session="createNewSession"
					@delete-session="deleteSession"
			/>
			
			<div class="chat-area">
				<div class="chat-container">
					<div class="chat-status">
						<div v-if="currentCharacter" class="status-info">
							<el-icon class="status-icon" size="16" color="#D4AF37">
								<ChatDotRound />
							</el-icon>
							<span class="status-text">正在与 <strong>{{ currentCharacter }}</strong> 对话</span>
						</div>
						<div v-else class="status-info empty">
							<el-icon class="status-icon" size="16" color="#CCCCCC">
								<ChatDotRound />
							</el-icon>
							<span class="status-text">选择角色开始魔法对话</span>
						</div>
					</div>
					
					<div class="messages-container" ref="messagesContainer">
						<div v-for="message in messages" :key="message.id">
							<MessageItem
									:message="message"
									:playing-message-id="playingMessageId"
									@play-message="playMessage"
							/>
						</div>
						
						<div v-if="isStreaming" class="loading-message">
							<el-icon class="loading-icon" size="24" color="#D4AF37">
								<Loading />
							</el-icon>
							<span class="loading-text">AI正在施法中...</span>
						</div>
						
						<div v-if="messages.length === 0 && !isStreaming" class="empty-chat">
							<el-icon size="64" color="#D4AF37">
								<MagicStick />
							</el-icon>
							<h3 class="empty-title">开始你的魔法之旅</h3>
							<p class="empty-description">
								{{ currentCharacter ? `与${currentCharacter}开始对话吧！` : '请先选择一个魔法角色' }}
							</p>
						</div>
					</div>
					
					<ChatInput
							v-model:inputText="inputText"
							:is-loading="isStreaming"
							:is-recording="isRecording"
							@send-message="sendMessage"
							@toggle-recording="toggleRecording"
					/>
				</div>
			</div>
		</div>
	</div>
</template>

<script setup>
import { ref, onMounted, nextTick, onUnmounted } from 'vue'
import { useRouter } from 'vue-router'
// 新增: 导入 ElLoading
import { ElMessage, ElMessageBox, ElLoading } from 'element-plus'
import { Loading, ChatDotRound, MagicStick } from '@element-plus/icons-vue'
import { websocketService } from '@/services/websocket'
import { audioService } from '@/utils/audioService'
import * as api from '@/services/api'
import CharacterSelector from './CharacterSelector.vue'
import HistoryPanel from './HistoryPanel.vue'
import MessageItem from './MessageItem.vue'
import ChatInput from './ChatInput.vue'

const router = useRouter()
const messagesContainer = ref(null)

// 状态管理
const currentCharacter = ref('')
const currentConversationId = ref(null)
const currentSessionId = ref(null)
const characters = ref([])
const chatSessions = ref([])
const messages = ref([])
const inputText = ref('')
const isStreaming = ref(false)
const isRecording = ref(false)
const playingMessageId = ref('')
const mediaRecorder = ref(null)
const currentStreamingMessage = ref(null)

// 初始化
onMounted(async () => {
	await loadCharacters()
	await loadChatHistory()
	setupWebSocketHandlers()
	
	// 设置音频播放回调
	audioService.onPlayEnd = (messageId) => {
		playingMessageId.value = ''
	}
})

// 清理
onUnmounted(() => {
	websocketService.disconnect()
	if (mediaRecorder.value && mediaRecorder.value.state === 'recording') {
		mediaRecorder.value.stop()
	}
})

// 加载角色列表
async function loadCharacters() {
	try {
		characters.value = await api.getCharacters()
	} catch (error) {
		console.error('加载角色失败:', error)
	}
}

// 加载聊天历史
async function loadChatHistory() {
	try {
		const history = await api.getChatHistory()
		chatSessions.value = history
	} catch (error) {
		console.error('加载聊天历史失败:', error)
	}
}

// 设置WebSocket消息处理器
function setupWebSocketHandlers() {
	// 历史消息
	websocketService.onMessage('history', (historyMessages) => {
		messages.value = historyMessages.map(msg => ({
			id: `msg_${Date.now()}_${Math.random()}`,
			content: msg.content,
			type: msg.role === 'user' ? 'user' : 'assistant',
			audioUrl: msg.audio_url,
			timestamp: msg.created_at
		}))
		scrollToBottom()
	})
	
	// 文本流
	websocketService.onMessage('text_stream', (content) => {
		if (currentStreamingMessage.value) {
			currentStreamingMessage.value.content += content
			scrollToBottom()
		}
	})
	
	// 实时音频流
	websocketService.onMessage('audio_stream', (base64Data) => {
		if (currentStreamingMessage.value) {
			// 开始播放时设置UI状态
			if (!audioService.isPlayingMessage(currentStreamingMessage.value.id)) {
				playingMessageId.value = currentStreamingMessage.value.id
			}
			// 处理音频块
			audioService.processAudioChunk(base64Data, currentStreamingMessage.value.id)
		}
	})

	// 音频流结束
	websocketService.onMessage('audio_stream_end', () => {
		if (currentStreamingMessage.value) {
			audioService.endStream(currentStreamingMessage.value.id)
		}
	})

	// 音频完成
	websocketService.onMessage('audio_complete', (audioUrl) => {
		if (currentStreamingMessage.value) {
			currentStreamingMessage.value.audioUrl = audioUrl
			isStreaming.value = false
			currentStreamingMessage.value = null
		}
	})
	
	// 转录结果
	websocketService.onMessage('transcription', (content) => {
		// 更新最后一条用户消息的内容
		const lastUserMessage = [...messages.value].reverse().find(m => m.type === 'user')
		if (lastUserMessage && lastUserMessage.content === '🎤 语音消息') {
			lastUserMessage.content = content
		}
	})
}

// 选择角色
async function selectCharacter(characterName) {
	try {
		// 如果是同一个角色，不重复选择
		if (currentCharacter.value === characterName) {
			return
		}
		
		// 只获取角色信息，不创建对话
		const characters = await api.getCharacters()
		const character = characters.find(c => c.name === characterName)
		
		if (!character) {
			ElMessage.error('角色不存在')
			return
		}
		
		// 设置当前角色并清空消息
		currentCharacter.value = character.name
		currentConversationId.value = null // 清空对话ID，等发送消息时创建
		messages.value = []
		
		// 断开现有WebSocket连接
		websocketService.disconnect()
		
		ElMessage.success(`已选择角色：${character.name}`)
		
	} catch (error) {
		ElMessage.error('选择角色失败')
	}
}

// 发送消息
async function sendMessage() {
	if (!inputText.value.trim() || isStreaming.value) return
	
	const messageContent = inputText.value
	inputText.value = ''
	
	// 如果没有对话ID，先创建对话
	if (!currentConversationId.value) {
		if (!currentCharacter.value) {
			ElMessage.error('请先选择一个角色')
			return
		}
		
		try {
			// 创建对话
			const result = await api.selectCharacter(currentCharacter.value)
			currentConversationId.value = result.conversation.id
			
			// 连接WebSocket并等待连接建立
			websocketService.connect(currentConversationId.value)
			
			// 等待WebSocket连接建立
			await new Promise((resolve, reject) => {
				let attempts = 0
				const maxAttempts = 30 // 3秒超时
				
				const checkConnection = () => {
					attempts++
					if (websocketService.getConnectionStatus().connected) {
						resolve()
					} else if (attempts >= maxAttempts) {
						reject(new Error('WebSocket连接超时'))
					} else {
						setTimeout(checkConnection, 100)
					}
				}
				
				checkConnection()
			})
		} catch (error) {
			console.error('创建对话或连接失败:', error)
			ElMessage.error('创建对话失败')
			inputText.value = messageContent // 恢复输入内容
			return
		}
	}
	
	const userMessage = {
		id: `msg_${Date.now()}`,
		content: messageContent,
		type: 'user',
		timestamp: new Date().toISOString()
	}
	
	messages.value.push(userMessage)
	
	// 创建AI消息占位符
	const aiMessage = {
		id: `msg_${Date.now() + 1}`,
		content: '',
		type: 'assistant',
		timestamp: new Date().toISOString()
	}
	messages.value.push(aiMessage)
	currentStreamingMessage.value = aiMessage
	isStreaming.value = true
	
	// 发送消息
	const success = websocketService.sendTextMessage(messageContent)
	if (!success) {
		ElMessage.error('消息发送失败，请重试')
		isStreaming.value = false
		currentStreamingMessage.value = null
		// 移除失败的AI消息
		messages.value.pop()
	}
	
	scrollToBottom()
}

// 录音控制
async function toggleRecording() {
	if (isRecording.value) {
		stopRecording()
	} else {
		await startRecording()
	}
}

// 开始录音
async function startRecording() {
	try {
		// 如果没有对话ID，先创建对话
		if (!currentConversationId.value) {
			if (!currentCharacter.value) {
				ElMessage.error('请先选择一个角色')
				return
			}
			
			try {
				// 创建对话
				const result = await api.selectCharacter(currentCharacter.value)
				currentConversationId.value = result.conversation.id
				
				// 连接WebSocket并等待连接建立
				websocketService.connect(currentConversationId.value)
				
				// 等待WebSocket连接建立
				await new Promise((resolve, reject) => {
					let attempts = 0
					const maxAttempts = 30 // 3秒超时
					
					const checkConnection = () => {
						attempts++
						if (websocketService.getConnectionStatus().connected) {
							resolve()
						} else if (attempts >= maxAttempts) {
							reject(new Error('WebSocket连接超时'))
						} else {
							setTimeout(checkConnection, 100)
						}
					}
					
					checkConnection()
				})
			} catch (error) {
				console.error('创建对话或连接失败:', error)
				ElMessage.error('创建对话失败')
				return
			}
		}
		
		const stream = await navigator.mediaDevices.getUserMedia({
			audio: {
				echoCancellation: true,
				noiseSuppression: true,
				sampleRate: 16000
			}
		})
		
		mediaRecorder.value = new MediaRecorder(stream, {
			mimeType: 'audio/webm'
		})
		
		const audioChunks = []
		const startTime = Date.now() // 记录开始时间
		
		mediaRecorder.value.ondataavailable = (event) => {
			if (event.data.size > 0) {
				audioChunks.push(event.data)
			}
		}
		
		mediaRecorder.value.onstop = async () => {
			stream.getTracks().forEach(track => track.stop())
			
			const recordingDuration = Date.now() - startTime
			
			// 检查录音时长，少于1秒认为是误触
			if (audioChunks.length === 0 || recordingDuration < 1000) {
				isRecording.value = false
				if (recordingDuration < 1000) {
					ElMessage.warning('录音时间太短，请长按录音按钮至少1秒')
				}
				return
			}
			
			const audioBlob = new Blob(audioChunks, { type: 'audio/webm' })
			
			const localAudioUrl = URL.createObjectURL(audioBlob)
			
			const arrayBuffer = await audioBlob.arrayBuffer()
			
			// 添加用户语音消息
			const userMessage = {
				id: `msg_${Date.now()}`,
				content: '🎤 语音消息',
				type: 'user',
				timestamp: new Date().toISOString(),
				audioUrl: localAudioUrl
			}
			messages.value.push(userMessage)
			
			// 添加AI消息占位符
			const aiMessage = {
				id: `msg_${Date.now() + 1}`,
				content: '',
				type: 'assistant',
				timestamp: new Date().toISOString()
			}
			messages.value.push(aiMessage)
			currentStreamingMessage.value = aiMessage
			isStreaming.value = true
			
			// 发送音频数据
			const success = websocketService.sendAudioMessage(arrayBuffer)
			if (!success) {
				ElMessage.error('音频发送失败，请重试')
				isStreaming.value = false
				currentStreamingMessage.value = null
				// 移除失败的AI消息
				messages.value.pop()
			}
			isRecording.value = false
		}
		
		mediaRecorder.value.start()
		isRecording.value = true
		ElMessage.success('开始录音')
		
	} catch (error) {
		console.error('启动录音失败:', error)
		ElMessage.error('无法访问麦克风')
		isRecording.value = false
	}
}

// 停止录音
function stopRecording() {
	if (mediaRecorder.value && mediaRecorder.value.state === 'recording') {
		mediaRecorder.value.stop()
	}
}

// 播放消息音频
async function playMessage(message) {
	if (playingMessageId.value === message.id) {
		audioService.stopAudio()
		playingMessageId.value = ''
		return
	}
	
	if (message.audioUrl) {
		playingMessageId.value = message.id
		try {
			await audioService.playAudio(message.audioUrl, message.id)
		} catch (error) {
			playingMessageId.value = ''
			ElMessage.error('音频播放失败')
		}
	}
}

// 加载会话
function loadSession(sessionId) {
	const session = chatSessions.value.find(s => s.id === sessionId)
	if (session) {
		currentSessionId.value = sessionId
		messages.value = session.messages || []
		
		// 恢复会话状态
		const conversationId = sessionId.replace('session_', '')
		currentConversationId.value = conversationId
		currentCharacter.value = session.character || ''
		
		// 连接WebSocket
		if (currentConversationId.value) {
			websocketService.connect(currentConversationId.value)
		}
		
		scrollToBottom()
		ElMessage.success(`已加载会话：${session.title}`)
	}
}

// 创建新会话
function createNewSession() {
	messages.value = []
	currentSessionId.value = null
	currentConversationId.value = null
	// 保持当前角色选择，但清除对话ID
	websocketService.disconnect()
	ElMessage.success('已创建新会话')
}

// 删除会话
async function deleteSession(sessionId) {
	try {
		await ElMessageBox.confirm('确定要删除这个会话吗？', '确认删除')
		await api.deleteConversation(sessionId)
		
		if (currentSessionId.value === sessionId) {
			createNewSession()
		}
		
		await loadChatHistory()
		ElMessage.success('会话删除成功')
	} catch (error) {
		if (error !== 'cancel') {
			ElMessage.error('删除失败')
		}
	}
}

// 退出登录
async function handleLogout() {
	try {
		await ElMessageBox.confirm('确定要退出登录吗？', '确认')
		localStorage.clear()
		router.push('/login')
	} catch (error) {
		// 用户取消
	}
}

// 跳转管理页面
function goToCharacterManagement() {
	router.push('/characters')
}

function goToKnowledgeManagement() {
	router.push('/knowledge')
}

// 滚动到底部
function scrollToBottom() {
	nextTick(() => {
		if (messagesContainer.value) {
			messagesContainer.value.scrollTop = messagesContainer.value.scrollHeight
		}
	})
}

// --- 语音克隆相关函数 ---

// 触发文件选择的辅助函数
function promptForFile(title = '选择音频文件') {
	return new Promise((resolve, reject) => {
		const input = document.createElement('input');
		input.type = 'file';
		input.accept = 'audio/*'; // 接受所有音频类型
		input.onchange = (e) => {
			const file = e.target.files[0];
			if (file) {
				// 文件大小限制
				if (file.size > 10 * 1024 * 1024) { // 10MB
					ElMessage.error('音频文件不能超过10MB');
					reject(new Error('文件过大'));
					return;
				}
				resolve(file);
			} else {
				reject(new Error('未选择文件'));
			}
		};
		// 模拟点击以打开文件对话框
		input.click();
	});
}

// 读取文件并转为Base64的辅助函数
function readFileAsBase64(file) {
	return new Promise((resolve, reject) => {
		const reader = new FileReader();
		reader.onload = () => {
			const base64String = reader.result.split(',')[1];
			resolve(base64String);
		};
		reader.onerror = (error) => reject(error);
		reader.readAsDataURL(file);
	});
}

// Base64转Blob对象的辅助函数
function base64ToBlob(base64, contentType = '', sliceSize = 512) {
	const byteCharacters = atob(base64);
	const byteArrays = [];
	for (let offset = 0; offset < byteCharacters.length; offset += sliceSize) {
		const slice = byteCharacters.slice(offset, offset + sliceSize);
		const byteNumbers = new Array(slice.length);
		for (let i = 0; i < slice.length; i++) {
			byteNumbers[i] = slice.charCodeAt(i);
		}
		const byteArray = new Uint8Array(byteNumbers);
		byteArrays.push(byteArray);
	}
	return new Blob(byteArrays, { type: contentType });
}

// 处理语音克隆的主函数
async function handleCloneVoice() {
	// 用于存储所有API参数
	const payload = {};
	
	// --- 第1步: 获取合成文本 ---
	try {
		const { value } = await ElMessageBox.prompt('请输入需要合成的文本', '语音克隆 - 第1步', {
			confirmButtonText: '下一步 (选择音色参考音频)',
			cancelButtonText: '取消',
			inputPlaceholder: '例如：你好，这是一个语音克隆测试。',
			inputValidator: (val) => val.trim() !== '',
			inputErrorMessage: '合成文本不能为空',
		});
		payload.text = value;
	} catch {
		ElMessage.info('已取消语音克隆');
		return;
	}
	
	// --- 第2步: 获取音色参考音频 ---
	try {
		const file = await promptForFile('选择音色参考音频');
		payload.voice_base64 = await readFileAsBase64(file);
	} catch (error) {
		if (error.message !== '文件过大') {
			ElMessage.info('已取消文件选择');
		}
		return;
	}
	
	// --- 第3步: 询问是否进行高级设置 ---
	try {
		await ElMessageBox.confirm('基础设置已完成。是否需要进行情绪、时长等高级设置？', '高级设置', {
			confirmButtonText: '是，进行高级设置',
			cancelButtonText: '否，直接开始合成',
			type: 'info',
		});
	} catch {
		// 用户选择 "否"，直接开始合成
		await executeTTS(payload);
		return;
	}
	
	// --- 第4步: 高级设置流程 ---
	try {
		// 4.1 情绪文本
		const { value: emoText, action: emoTextAction } = await ElMessageBox.prompt(
				'请输入情绪参考文本（选填）',
				'高级设置 - 情绪文本',
				{
					confirmButtonText: '确认',
					cancelButtonText: '跳过',
					inputPlaceholder: '例如：你吓死我了！',
					distinguishCancelAndClose: true,
				}
		);
		if (emoTextAction === 'confirm' && emoText.trim()) {
			payload.emo_text = emoText;
		} else {
			// 4.2 情绪音频 (仅在未设置情绪文本时询问)
			await ElMessageBox.confirm('是否使用情绪参考音频？', '高级设置 - 情绪音频', {
				confirmButtonText: '是',
				cancelButtonText: '否',
			});
			const emoFile = await promptForFile('选择情绪参考音频');
			payload.emo_audio_base64 = await readFileAsBase64(emoFile);
		}
	} catch (error) {
		if (error && error.message && error.message.includes('未选择文件')) {
			// 允许用户不选择情绪音频文件并继续
		} else if (error !== 'cancel' && error !== 'close') {
			// 如果不是简单的跳过或取消，则停止流程
			ElMessage.info('已跳过情绪设置');
		}
	}
	
	try {
		// 4.3 情绪向量 (仅在未设置前两种情绪时询问)
		if (!payload.emo_text && !payload.emo_audio_base64) {
			const { value: emoVectorStr } = await ElMessageBox.prompt(
					'请输入8维情绪向量，用逗号分隔（选填）',
					'高级设置 - 情绪向量',
					{
						confirmButtonText: '确认',
						cancelButtonText: '跳过',
						inputPlaceholder: '[开心,愤怒,悲伤,恐惧,厌恶,忧郁,惊讶,平静]',
						inputValidator: (val) => {
							if (!val) return true; // 允许为空
							const parts = val.split(',').map(Number);
							return parts.length === 8 && parts.every(p => !isNaN(p));
						},
						inputErrorMessage: '格式错误，请输入8个用逗号分隔的数字',
					}
			);
			if (emoVectorStr) {
				payload.emotion_vector = emoVectorStr.split(',').map(Number);
			}
		}
		
		// 4.4 情绪强度 (仅在设置了任意一种情绪时询问)
		if (payload.emo_text || payload.emo_audio_base64 || payload.emotion_vector) {
			const { value: emoAlpha } = await ElMessageBox.prompt(
					'请输入情绪强度 (0.0 - 1.0)',
					'高级设置 - 情绪强度',
					{
						confirmButtonText: '确认',
						cancelButtonText: '使用默认值(0.7)',
						inputValue: '0.7',
						inputValidator: (val) => {
							const num = parseFloat(val);
							return !isNaN(num) && num >= 0 && num <= 1;
						},
						inputErrorMessage: '请输入0到1之间的数字',
					}
			);
			if (emoAlpha) {
				payload.emo_alpha = parseFloat(emoAlpha);
			}
		}
		
		// 4.5 Token数量
		const { value: tokenCount } = await ElMessageBox.prompt(
				'请输入精确控制的Token数（选填）',
				'高级设置 - 时长控制',
				{
					confirmButtonText: '确认',
					cancelButtonText: '跳过',
					inputValidator: (val) => {
						if (!val) return true;
						return /^\d+$/.test(val);
					},
					inputErrorMessage: '请输入一个正整数',
				}
		);
		if (tokenCount) {
			payload.token_count = parseInt(tokenCount, 10);
		}
		
		// 4.6 随机性
		await ElMessageBox.confirm('是否启用随机性以增加多样性？', '高级设置 - 随机性', {
			confirmButtonText: '是',
			cancelButtonText: '否',
		});
		payload.use_random = true;
		
	} catch (action) {
		if (action === 'cancel') {
			// 用户在随机性设置时点了“否”
			payload.use_random = false;
		} else {
			// 其他情况，如在前面步骤点了跳过或关闭
			ElMessage.info('部分高级设置已跳过');
		}
	}
	
	// --- 第5步: 执行合成 ---
	await executeTTS(payload);
}

// 语音合成执行函数
async function executeTTS(payload) {
	const loading = ElLoading.service({
		lock: true,
		text: '克隆魔法正在施展中...',
		background: 'rgba(0, 0, 0, 0.7)',
	});
	
	try {
		const response = await fetch('http://127.0.0.1:6006/tts', {
			method: 'POST',
			headers: {
				'Content-Type': 'application/json',
			},
			body: JSON.stringify(payload),
		});
		
		if (!response.ok) {
			const errorData = await response.json();
			throw new Error(errorData.detail || `服务器错误: ${response.status}`);
		}
		
		const result = await response.json();
		
		if (result.success && result.audio_base64) {
			const audioBlob = base64ToBlob(result.audio_base64, 'audio/wav');
			const audioUrl = URL.createObjectURL(audioBlob);
			
			await ElMessageBox.alert('语音克隆成功！点击下方按钮播放或下载。', '克隆完成', {
				confirmButtonText: '播放',
				showCancelButton: true,
				cancelButtonText: '下载',
				distinguishCancelAndClose: true,
			}).then(() => {
				const audio = new Audio(audioUrl);
				audio.play();
			}).catch((action) => {
				if (action === 'cancel') { // 点击了下载
					const a = document.createElement('a');
					a.href = audioUrl;
					a.download = `clone_${Date.now()}.wav`;
					document.body.appendChild(a);
					a.click();
					document.body.removeChild(a);
				}
			});
			
		} else {
			throw new Error('API返回失败或缺少音频数据');
		}
	} catch (error) {
		console.error('语音克隆失败:', error);
		ElMessage.error(`克隆失败: ${error.message}`);
	} finally {
		loading.close();
	}
}

</script>

<style scoped>
.app-layout {
	display: flex;
	flex-direction: column;
	height: 100vh;
	/* 移除背景图片，使用纯色背景 */
	background: #f5f5f5;
}

.main-layout {
	display: flex;
	flex: 1;
	overflow: hidden;
	/* 完全贴合，无间隙 */
}

.chat-area {
	flex: 1;
	display: flex;
	/* 移除所有内边距 */
	min-width: 0; /* 防止flex项目溢出 */
}

.chat-container {
	flex: 1;
	display: flex;
	flex-direction: column;
	background: white;
	/* 移除圆角和阴影，完全贴合 */
	overflow: hidden;
}

.chat-status {
	padding: 12px 20px;
	background: #f9f9f9;
	/* 使用简单的分隔线 */
	border-bottom: 1px solid #e0e0e0;
}

.status-info {
	display: flex;
	align-items: center;
	gap: 8px;
}

.status-info.empty {
	opacity: 0.7;
}

.status-text {
	font-size: 14px;
	color: #8B4513;
	font-weight: 500;
}

.messages-container {
	flex: 1;
	padding: 16px 20px;
	overflow-y: auto;
	display: flex;
	flex-direction: column;
	gap: 16px;
	position: relative;
}

.messages-container::-webkit-scrollbar {
	width: 6px;
}

.messages-container::-webkit-scrollbar-track {
	background: transparent;
}

.messages-container::-webkit-scrollbar-thumb {
	background: #D4AF37;
	border-radius: 3px;
}

.messages-container::-webkit-scrollbar-thumb:hover {
	background: #B8860B;
}

.loading-message {
	display: flex;
	align-items: center;
	gap: 12px;
	padding: 16px;
	background: rgba(212, 175, 55, 0.1);
	border-radius: 16px;
	border: 1px solid #D4AF37;
}

.loading-icon {
	animation: spin 1s linear infinite;
}

@keyframes spin {
	from { transform: rotate(0deg); }
	to { transform: rotate(360deg); }
}

.loading-text {
	color: #8B4513;
	font-weight: 500;
}

.empty-chat {
	display: flex;
	flex-direction: column;
	align-items: center;
	justify-content: center;
	flex: 1;
	text-align: center;
	color: #666;
	padding: 40px;
}

.empty-title {
	margin: 16px 0 8px 0;
	font-size: 24px;
	font-weight: 600;
	color: #8B4513;
}

.empty-description {
	margin: 0;
	font-size: 16px;
	opacity: 0.8;
	max-width: 300px;
	line-height: 1.5;
}

/* 响应式设计 */
@media (max-width: 768px) {
	.main-layout {
		flex-direction: column;
	}
	
	.chat-area {
		padding: 8px;
	}
	
	.messages-container {
		padding: 12px 16px;
	}
	
	.chat-status {
		padding: 8px 16px;
	}
}

/* 针对更小屏幕的额外优化 */
@media (max-width: 480px) {
	.chat-area {
		padding: 6px;
	}
	
	.messages-container {
		padding: 8px 12px;
	}
}

/* 优化动画效果 */
.chat-container {
	animation: slideIn 0.3s ease-out;
}

@keyframes slideIn {
	from {
		opacity: 0;
		transform: translateY(20px);
	}
	to {
		opacity: 1;
		transform: translateY(0);
	}
}

/* 移除磨砂玻璃效果，保持简洁 */
</style>